import socket  
import time  
import sys

def test_max_connections(host, port):  
    sockets = []  
    max_connections = 0  
    start_time = time.time()  # 记录开始时间  

    while True:  
        try:  
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
            s.connect((host, port))  
            sockets.append(s)  
            max_connections += 1  

            # 每隔60秒输出一次当前连接数  
            if time.time() - start_time > 60:  
                print(f"Current connections: {max_connections}")  
                start_time = time.time()  

        except socket.error as e:  
            print(f"Reached maximum connections: {max_connections}")  
            print(f"Last error message: {e}")  
            # 如果服务器关闭连接，我们假定服务器已经停止运行  
            if "Connection reset by peer" in str(e):  
                print("Server has stopped. Exiting.")  
            sys.exit(1)  # 结束脚本运行

    # 关闭所有打开的连接  
    for s in sockets:  
        s.close()  

if __name__ == "__main__":  
    test_max_connections("127.0.0.1", 8888)
